package cn.com.taiji.oospub.wechat.common.helper;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.pub.SecurityUtil;
import cn.com.taiji.pub.TimeTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 * @author Peream <br>
 *         Create Time：2010-11-15 上午11:03:11<br>
 *         <a href="mailto:peream@gmail.com">peream@gmail.com</a>
 * @since 1.0
 * @version 1.0
 */
public class WXLoginHelper
{
	protected static Logger logger = LoggerFactory.getLogger(WXLoginHelper.class);

	public static boolean hasLogin(HttpServletRequest request)
	{
		MemberBaseInfo entity = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
		return (entity != null && StringUtils.hasText(entity.getId()));
	}

	public static void setSession(HttpServletRequest request, MemberBaseInfo entity)
	{
		Assert.notNull(entity);
		String ip = request.getRemoteHost();
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
		WebUtils.setSessionAttribute(request, SessionNames.LOGIN_IP, ip);
		WebUtils.setSessionAttribute(request, SessionNames.LOGIN_TIME, TimeTools.toTimeStr());
		WebUtils.setSessionAttribute(request, SessionNames.LOGIN_USER, entity);

		logger.debug("Set session attributes after login:{}", entity);
	}

	public static boolean isPassValid(String pass, MemberBaseInfo entity)
	{
		if (entity == null) {
            return false;
        }
		String secPasswd = SecurityUtil.encryptStr(pass, SecurityUtil.HashType.SHA_1, true);
		return secPasswd.equals(entity.getPasswd());
	}
}

